package com.example.springbootlucenedemo.common.lucene.impl;

import com.example.springbootlucenedemo.common.lucene.bean.EntityUtil;
import com.example.springbootlucenedemo.common.lucene.bean.Message;
import com.example.springbootlucenedemo.common.lucene.conf.LuceneConf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author heh
 */
@Slf4j
@Component
@ConditionalOnProperty(name="spring.lucene.pub/subModel",havingValue="true",matchIfMissing = false)
public class MessageReceiver {
    private LuceneConf luceneConf;
    private IndexServiceImpl indexService;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    public MessageReceiver (LuceneConf luceneConf){
        this.luceneConf =luceneConf;
        this.indexService = new IndexServiceImpl(this.luceneConf);
    }
    public void handleMessage (String message){
        log.debug(message);
    }

    public void addDocument(String message){
        log.debug(message);
        Object object = new Message(message).getObject();
        indexService.addDocument(object);
        redisTemplate.opsForValue().setBit(EntityUtil.getLuceneIndexPath(EntityUtil.getLuceneIndexPath(object)),  EntityUtil.hashByPrimarykey(object), true);

    }
    public void deleteDocument(String message){
        log.debug(message);
        Object object = new Message(message).getObject();
        indexService.deleteDocument(object);
        redisTemplate.opsForValue().setBit(EntityUtil.getLuceneIndexPath(EntityUtil.getLuceneIndexPath(object)),  EntityUtil.hashByPrimarykey(object), false);

    }
    public void updateDocument(String message){
        log.debug(message);
        indexService.updateDocument(new Message(message).getObject());
    }
}
